﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Tsanie.OsuDevice.Models;
using Tsanie.OsuDevice.Utils;

namespace Tsanie.OsuDevice.Network {
    class Account {
        public static void Login(string username, string password, bool autologin, Action<UserInfo> loginFunc) {
#if DEBUG
            Console.WriteLine("Request start.");
#endif
            string ssid = Guid.NewGuid().ToString("N");
            HttpHelper.BeginConnect(Config.HttpHost + "/forum/ucp.php?mode=login", (request) => {
                request.AllowAutoRedirect = false;
                request.Method = "POST";
                request.Headers["Cookie"] = "phpbb3_2cjk5_u=1; phpbb3_2cjk5_k=; phpbb3_2cjk5_sid=" + ssid;
                request.Referer = Config.HttpHost;
                request.Headers["Cache_Control"] = "no-cache";
                request.ContentType = "application/x-www-form-urlencoded";
                string data = "username="
                    + HttpUtility.UrlEncode(username) + "&password="
                    + HttpUtility.UrlEncode(password) + (autologin ? "&autologin=on" : "")
                    + "&redirect=%2F&sid=" + ssid + "&login=login";
                byte[] bs = Encoding.ASCII.GetBytes(data);
                request.ContentLength = bs.Length;
                using (Stream loginStream = request.GetRequestStream()) {
                    loginStream.Write(bs, 0, bs.Length);
                    loginStream.Close();
                }
#if DEBUG
                Console.WriteLine("Request done! => {0}", data);
#endif
            }, (state) => {
                string setcookie = state.Response.Headers["Set-Cookie"];
                UserInfo uinfo = new UserInfo();
                if (string.IsNullOrEmpty(setcookie)) {
                    // 未成功登录
                    if (loginFunc != null)
                        loginFunc(null);
                    return;
                }
                foreach (string cookie in setcookie.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)) {
                    string[] kv = cookie.Trim().Split('=');
                    if (kv.Length == 2 && kv[0].StartsWith("phpbb3_") && kv[1] != "deleted") {
                        switch (kv[0]) {
                            case "phpbb3_2cjk5_u":
                                uinfo.Uid = kv[1].Trim();
                                break;
                            case "phpbb3_2cjk5_k":
                                uinfo.Key = kv[1].Trim();
                                break;
                            case "phpbb3_2cjk5_sid":
                                uinfo.Sid = kv[1].Trim();
                                break;
                        }
                    }
                }
                Config.Cookies = "phpbb3_2cjk5_u=" + uinfo.Uid + "; phpbb3_2cjk5_k=" + uinfo.Key + "; phpbb3_2cjk5_sid=" + uinfo.Sid;
                if (loginFunc != null)
                    loginFunc(uinfo);
            }, (ex) => {
                if (loginFunc != null)
                    loginFunc(null);
            });
        }

        public static void Logout(Action<string> logoutFunc) {
            // TODO: 从Cookie里获取sid
            HttpHelper.BeginConnect(Config.HttpHost + "/forum/ucp.php?mode=logout&sid=" + ("##sid##"), (request) => {
                request.Referer = Config.HttpHost;
                request.Headers["Cookie"] = Config.Cookies;
            }, (state) => {
                // TODO: 登出成功

            }, (ex) => {
                LogUtil.Error(ex, null);
                if (logoutFunc != null)
                    logoutFunc(null);
            });
        }
    }
}
